<template>
    <div class="custom-dropdown" @mouseleave="closeDropdown">
        <div class="dropdown-trigger" @click="toggleDropdown" @mouseenter="openDropdown">
            <slot name="trigger">
                <span>{{ triggerText }}</span>
            </slot>
            <i class="arrow-down"></i>
        </div>  
        <ul class="dropdown-menu" v-show="isOpen" @mouseenter="openDropdown">
            <li v-for="(item, index) in menuItems" :key="index" class="dropdown-item" @click="handleItemClick(item)"
                @mouseenter="hoverItem(index)" :style="{ backgroundColor: hoveredIndex === index ? '#27ba9b' : '' }">
                <i :class="item.iconClass" class="icon"></i> <!-- 添加图标 -->
                {{ item.label }}
            </li>
        </ul>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';

const props = defineProps({
    menuItems: {
        type: Array,
        required: true,
        default: () => [],
    },
    triggerText: {
        type: String,
        default: '请选择',
    },
});

const emit = defineEmits(['item-click']);

const isOpen = ref(false);
const hoveredIndex = ref(-1);

const toggleDropdown = () => {
    isOpen.value = !isOpen.value;
};

const openDropdown = () => {
    isOpen.value = true;
};

const closeDropdown = () => {
    isOpen.value = false;
    hoveredIndex.value = -1;
};

const handleItemClick = (item) => {
    emit('item-click', item);
    closeDropdown();
};

const hoverItem = (index) => {
    hoveredIndex.value = index;
};

const handleClickOutside = (event) => {
    if (!event.target.closest('.custom-dropdown')) {
        closeDropdown();
    }
};

onMounted(() => {
    document.addEventListener('click', handleClickOutside);
});

onUnmounted(() => {
    document.removeEventListener('click', handleClickOutside);
});
</script>

<style scoped lang="scss">
.custom-dropdown {
    position: relative;
    display: inline-block;
}

.dropdown-trigger {
    border-left: 2px solid #666;
    padding: 0 15px;
    color: #cdcdcd;
    line-height: 1;
    display: inline-block;
}
.dropdown-menu {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 10;
    min-width: 100px;
    border: 1px solid #ccc;
    background-color: #fff;
    padding: 0;
    margin: 0;
    list-style: none;
    z-index: 1000;
}

.dropdown-item {
    text-align: center;
    padding: 8px 12px;
    cursor: pointer;
    white-space: nowrap;
    &.icon{
        color: #27ba9b;
    }
}

.dropdown-item:hover {
    background-color: #27ba9b;
    color: #fff;
    transition: all 0.5s ease;
}
</style>